#include <bits/stdc++.h>
using namespace std;
const int N = 110;
int n, m;
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
int dis[N][N]; // 记录距离每个点到初始点的距离
int arr[N][N];
pair<int, int> pre[N][N]; // 记录该点的上个点
bool st[N][N];
void bfs(int x, int y)
{
    queue<pair<int, int>> pp;
    pp.push(make_pair(x, y));
    dis[x][y] = 0;
    pre[0][0] = make_pair(0, 0);
    st[x][y]=true;

    while (!pp.empty())
    {
        auto tem = pp.front();
        pp.pop();

        if(tem.first==n-1&&tem.second==m-1) return;
        for (int k = 0; k < 4; k++)
        {
            int x1 = tem.first + dx[k];
            int y1 = tem.second + dy[k];
            if (x1 >= 0 && x1 < n && y1 >= 0 && y1 < m && !st[x1][y1] && arr[x1][y1] == 0)
            {
                pp.push(make_pair(x1, y1));
                st[x1][y1]=true;
                dis[x1][y1] = dis[tem.first][tem.second] + 1;
                pre[x1][y1] = make_pair(tem.first, tem.second);
            }
        }
    }
}
int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> m;
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            cin >> arr[i][j];
        }
    }
    bfs(0, 0);
    cout << dis[n - 1][m - 1] << endl;
}